import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart' hide Action;

import 'action.dart';
import 'state.dart';

Effect<BottomSelectViewState> buildEffect() {
  return combineEffects(<Object, Effect<BottomSelectViewState>>{
    BottomSelectViewAction.onSearch: _onSearch,
    BottomSelectViewAction.onTap: _onTap,
  });
}

void _onTap(Action action, Context<BottomSelectViewState> ctx) {
  if (ctx.state.isSearching == false) {
    Navigator.pop(ctx.context,action.payload);
    return;
  }
  String value = ctx.state.searchItems[action.payload];
  Navigator.pop(ctx.context,ctx.state.items.indexOf(value));
}

void _onSearch(Action action, Context<BottomSelectViewState> ctx) {
  String value = action.payload;
  print(value);
  if (value.isEmpty) {
    ctx.state.isSearching = false;
    ctx.dispatch(BottomSelectViewActionCreator.onAction());
    return;
  }
  List<String> searchRes = [];
  for (String text in ctx.state.items) {
    if (text.contains(value)) {
      searchRes.add(text);
    }
  }
  ctx.state.isSearching = true;
  ctx.state.searchItems = searchRes;
  ctx.dispatch(BottomSelectViewActionCreator.onAction());
}
